package com.zbkj.crmeb.merchant.api.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.crmeb.core.utils.RedisUtil;
import com.crmeb.core.utils.TableNameUtil;
import com.github.pagehelper.PageHelper;
import com.taobao.pac.sdk.cp.dataobject.response.MODUAN_ORDER_CREATE.response;
import com.zbkj.crmeb.category.model.Category;
import com.zbkj.crmeb.category.request.CategorySearchRequest;
import com.zbkj.crmeb.category.service.CategoryService;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.front.request.IndexStoreProductSearchRequest;
import com.zbkj.crmeb.front.request.ProductRequest;
import com.zbkj.crmeb.front.response.IndexAdviceResponse;
import com.zbkj.crmeb.front.response.IndexInfoResponse;
import com.zbkj.crmeb.front.response.IndexProductBannerResponse;
import com.zbkj.crmeb.front.response.IndexProductStoreZoneResponse;
import com.zbkj.crmeb.merchant.admin.service.CustomShareService;
import com.zbkj.crmeb.merchant.api.service.MerIndexService;
import com.zbkj.crmeb.merchant.api.service.MerProductService;
import com.zbkj.crmeb.store.dao.StoreProductDao;
import com.zbkj.crmeb.store.model.ChannelCategoryConfig;
import com.zbkj.crmeb.store.model.ChannelStoreBrandConfig;
import com.zbkj.crmeb.store.model.CustomShare;
import com.zbkj.crmeb.store.model.StoreBanner;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreZone;
import com.zbkj.crmeb.store.request.StoreBrandRequest;
import com.zbkj.crmeb.store.service.ChannelCategoryConfigService;
import com.zbkj.crmeb.store.service.ChannelStoreBrandConfigService;
import com.zbkj.crmeb.store.service.StoreBannerService;
import com.zbkj.crmeb.store.service.StoreBrandService;
import com.zbkj.crmeb.store.service.StoreZoneService;
import com.zbkj.crmeb.store.utilService.OrderUtils;
import com.zbkj.crmeb.system.model.SystemConfig;
import com.zbkj.crmeb.system.service.SystemConfigService;
import com.zbkj.crmeb.system.service.SystemGroupDataService;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.service.UserService;

/**
* @author Mr.Zhang
* @Description IndexServiceImpl 接口实现
* @since 2020-04-13
*/
@Service
public class MerIndexServiceImpl implements MerIndexService {

    @Autowired
    private SystemGroupDataService systemGroupDataService;
    @Autowired
    private MerProductService productService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private UserService userService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    private StoreBannerService storeBannerService;
    @Autowired
    private StoreBrandService storeBrandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    ChannelStoreBrandConfigService channelStoreBrandConfigService;
    @Autowired
    private ChannelCategoryConfigService channelCategoryConfigService;
    @Autowired
    private StoreZoneService storeZoneService;
    @Autowired
    private StoreProductDao storeProductDao;
    @Autowired
    private CustomShareService customShareService;
    @Autowired
    private OrderUtils orderUtils;
    
    @Value("${order.yueMerIds}")
    private List<Integer> yueMerIds;

    /**
     * 首页产品的轮播图和产品信息
     * @param type integer 类型
     * @author Mr.Zhang
     * @since 2020-06-02
     * @return HashMap<String, Object>
     */
    @Override
    public IndexProductBannerResponse getProductBanner(int type, PageParamRequest pageParamRequest) {

        IndexProductBannerResponse indexProductBannerResponse = new IndexProductBannerResponse();
        IndexStoreProductSearchRequest request = new IndexStoreProductSearchRequest();
        int gid;
        String key;
        switch (type){
            case Constants.INDEX_RECOMMEND_BANNER: //精品推荐
                gid = Constants.GROUP_DATA_ID_INDEX_RECOMMEND_BANNER;
                key = Constants.INDEX_BAST_LIMIT;
                request.setIsBest(true);
                break;
            case Constants.INDEX_HOT_BANNER: //热门榜单
                gid = Constants.GROUP_DATA_ID_INDEX_HOT_BANNER;
                key = Constants.INDEX_HOT_LIMIT;
                request.setIsHot(true);
                break;
            case Constants.INDEX_NEW_BANNER: //首发新品
                gid = Constants.GROUP_DATA_ID_INDEX_NEW_BANNER;
                key = Constants.INDEX_FIRST_LIMIT;
                request.setIsNew(true);
                break;
            case Constants.INDEX_BENEFIT_BANNER: //促销单品
                gid = Constants.GROUP_DATA_ID_INDEX_BENEFIT_BANNER;
                key = Constants.INDEX_SALES_LIMIT;
                request.setIsBenefit(true);
                break;
            default:
                return null;
        }

        if(StringUtils.isNotBlank(key)){
            String num = systemConfigService.getValueByKey(Constants.INDEX_BAST_LIMIT);
            if(pageParamRequest.getLimit() == 0){
                //首页limit传0，则读取默认数据， 否则后台设置的首页配置不起作用
                pageParamRequest.setLimit(Integer.parseInt(num));
            }
        }

        indexProductBannerResponse.setBanner(systemGroupDataService.getListMapByGid(gid, null));
        indexProductBannerResponse.setList(productService.getIndexProduct(request, pageParamRequest, null).getList());
        return indexProductBannerResponse;
    }

    /**
     * 首页数据
     * @author Mr.Zhang
     * @since 2020-06-02
     * @return HashMap<String, Object>
     */
    @Override
    public IndexInfoResponse getIndexInfo(Integer merId, PageParamRequest pageParamRequest) {
        IndexInfoResponse indexInfoResponse =  new IndexInfoResponse();
        IndexStoreProductSearchRequest request = new IndexStoreProductSearchRequest();
        request.setIsBest(true);
        request.setMerId(merId);
        indexInfoResponse.setProductList(productService.getBestProductList(request, pageParamRequest).getList());
        // 缓存处理配置项
        indexInfoResponse.setLogoUrl(systemConfigService.getValueByKey(Constants.CONFIG_KEY_SITE_LOGO));

        User user = userService.getInfo();
        if(null != user){
            indexInfoResponse.setSubscribe(user.getSubscribe());
        }

        //新的banner列表
        StoreBanner storeBanner = new StoreBanner();
        storeBanner.setMerId(merId);
        indexInfoResponse.setBannerList(storeBannerService.getList(storeBanner));
        SystemConfig confing = systemConfigService.getOne(Wrappers.<SystemConfig>lambdaQuery()
                .eq(SystemConfig :: getName, Constants.CONFIG_INDEX+"_"+merId)
//                .eq(SystemConfig :: getFormId, merId)
                .last("LIMIT 1")
                );
        indexInfoResponse.setIndexConfig(null == confing ? "1" : confing.getValue());
        //多供应商详情
        SystemConfig configProductDetail = systemConfigService.getOne(Wrappers.<SystemConfig>lambdaQuery()
                .eq(SystemConfig :: getName, Constants.CONFIG_PRODUCT_DETAIL+"_"+merId)
//                .eq(SystemConfig :: getFormId, merId)
                .last("LIMIT 1")
                );
        indexInfoResponse.setProductDetailConfig(null == configProductDetail ? "1" : configProductDetail.getValue());
        ChannelMerchant channelMerchant = channelMerchantService.getById(merId);
        if (channelMerchant != null) {
            indexInfoResponse.setAppletType(channelMerchant.getAppletType());
            indexInfoResponse.setChannelType(channelMerchant.getChannelType());
            indexInfoResponse.setIsShowRate(channelMerchant.getIsShowRate());
        }
        // 余额支付开关
        if(-1 == yueMerIds.indexOf(merId)) {
        	indexInfoResponse.setYue(true);
        } else {
        	indexInfoResponse.setYue(false);
        }
    	indexInfoResponse.setPayType(orderUtils.getOrderPayType(request.getMerId()).getMsg());
        // 是否显示折扣
        SystemConfig showDisCountConfig  = systemConfigService.getOne(Wrappers.<SystemConfig>lambdaQuery()
                .eq(SystemConfig :: getName, Constants.CONFIG_KEY_SHOW_DISCOUNT+"_"+merId)
                //.eq(SystemConfig :: getFormId, 101)
                .eq(SystemConfig :: getStatus, false)
                .last("LIMIT 1")
        );
        indexInfoResponse.setShowDiscount(Objects.isNull(showDisCountConfig) || "1".equals(showDisCountConfig.getValue()) ? 1 : 0);

        return indexInfoResponse;
    }


    /**
     * 热门搜索
     * @author Mr.Zhang
     * @since 2020-06-03
     * @return List<HashMap<String, String>>
     */
    @Override
    public List<HashMap<String, Object>> hotKeywords(Integer merId) {

        return systemGroupDataService.getListMapByGid(Constants.GROUP_DATA_ID_INDEX_KEYWORDS, merId);
    }

    /**
     * 微信分享配置
     * @author Mr.Zhang
     * @since 2020-05-25
     * @return Object
     */
    @Override
    public HashMap<String, String> getShareConfig(Integer merId) {
        HashMap<String, String> map = new HashMap<>();
        //todo分享
        CustomShare customShare = customShareService.getOne(Wrappers.<CustomShare>lambdaQuery().eq(CustomShare::getMerId, merId).last("LIMIT 1"));
        if (customShare!=null&&customShare.getStatus()){
            map.put("img", customShare.getImg());
            map.put("title", customShare.getTitle());
            map.put("synopsis", customShare.getSynopsis());
        }else {
            HashMap<String, String> info = systemConfigService.info(Constants.CONFIG_FORM_ID_PUBLIC);
            if(info == null){
                throw new CrmebException("请配置公众号分享信息！");
            }

            map.put("img", info.get("wechat_share_img"));
            map.put("title", info.get("wechat_share_title"));
            map.put("synopsis", info.get("wechat_share_synopsis"));
        }

        return map;
    }

    @Override
    public IndexAdviceResponse getAdviceList(Integer merId) {
        IndexAdviceResponse response = new IndexAdviceResponse();
        //获取专区配置
        response.setStoreZoneStatus(0);
        LambdaQueryWrapper<SystemConfig> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SystemConfig::getFormId,merId);
        lambdaQueryWrapper.eq(SystemConfig::getName, Constants.CONFIG_KEY_APP_BAR_STATUS);
        SystemConfig systemConfig = systemConfigService.getOne(lambdaQueryWrapper);
        if(systemConfig != null && "1".equals(systemConfig.getValue())){
            response.setStoreZoneStatus(Integer.valueOf(systemConfig.getValue()));
            //查询导航栏专区数据
            LambdaQueryWrapper<StoreZone> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StoreZone::getMerId,merId);
            queryWrapper.eq(StoreZone::getIsDel,0);//未删除
            queryWrapper.eq(StoreZone::getIsAppBar,1);//导航专区展示
            queryWrapper.gt(StoreZone::getEndTime,new Date());
            queryWrapper.orderByDesc(StoreZone::getSort).orderByDesc(StoreZone::getUpdateTime);
            List<StoreZone> storeZoneList = storeZoneService.list(queryWrapper);

            List<StoreZone> newStoreZoneList =  new ArrayList<StoreZone>();

            for (StoreZone storeZone :storeZoneList){

                //查询商品
                ProductRequest request = new ProductRequest();
                request.setZoneId(storeZone.getId());
                request.setMerId(merId);
                request.setShowIds(Collections.singletonList(0));
                request.setTableNameMp(TableNameUtil.getProductMerName(merId));

                List<StoreProduct> storeProductList = storeProductDao.selectZoneProductList(request);

                if(storeProductList.size()>0){
                    newStoreZoneList.add(storeZone);
                }
            }

            response.setStoreZoneList(newStoreZoneList);
        }
        //获取首页专区
        LambdaQueryWrapper<StoreZone> storeZoneLambdaQueryWrapper = new LambdaQueryWrapper<>();
        storeZoneLambdaQueryWrapper.eq(StoreZone::getMerId,merId);
        storeZoneLambdaQueryWrapper.eq(StoreZone::getIsDel,0);//未删除
        storeZoneLambdaQueryWrapper.eq(StoreZone::getStatus,1);//首页展示
        storeZoneLambdaQueryWrapper.gt(StoreZone::getEndTime,new Date());
        storeZoneLambdaQueryWrapper.orderByDesc(StoreZone::getUpdateTime);
        storeZoneLambdaQueryWrapper.last("LIMIT 1");
        StoreZone storeZone = storeZoneService.getOne(storeZoneLambdaQueryWrapper);
        IndexProductStoreZoneResponse indexStoreZoneResponse = new IndexProductStoreZoneResponse();
        indexStoreZoneResponse.setStoreZone(storeZone);
        //查询对应专区下的商品
        if (storeZone != null){
            //查询未上架的商品ids
            ProductRequest request = new ProductRequest();
            request.setZoneId(storeZone.getId());
            request.setMerId(merId);
            request.setShowIds(Collections.singletonList(0));
            request.setTableNameMp(TableNameUtil.getProductMerName(merId));
            PageHelper.startPage(1, 4);//查询四条专区对应商品信息
            List<StoreProduct> storeProductList = storeProductDao.selectZoneProductList(request);
            indexStoreZoneResponse.setStoreProductList(storeProductList);
        }
        response.setIndexProductStoreZoneResponse(indexStoreZoneResponse);
        //首页分类推荐
        List<ChannelCategoryConfig> cateConfigs = channelCategoryConfigService.list(Wrappers.<ChannelCategoryConfig>lambdaQuery()
                .eq(ChannelCategoryConfig :: getMerId, merId)
                .eq(ChannelCategoryConfig::getIsAdvice,1)
                .eq(ChannelCategoryConfig::getStatus,1)
                .eq(ChannelCategoryConfig::getEnableFlag,1)
                .orderByDesc(ChannelCategoryConfig::getAdviceTime)
        );
        List<Integer> ids = cateConfigs.stream().map(ChannelCategoryConfig::getCateId).collect(Collectors.toList());
        List<Category> categoryList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(ids)){
            CategorySearchRequest categoryRequest = new CategorySearchRequest();
            categoryRequest.setIds(ids);
            categoryRequest.setType(1);
            categoryRequest.setStatus(true);
            categoryList = categoryService.getList(categoryRequest, new PageParamRequest());
            categoryList.sort(((o1, o2) -> {
                int io1 = ids.indexOf(o1.getId());
                int io2 = ids.indexOf(o2.getId());
                return io1 - io2;
            }));
        }
        response.setCategoryList(categoryList);
        // 获取商户品牌配置项
        List<ChannelStoreBrandConfig> configs = channelStoreBrandConfigService.list(Wrappers.<ChannelStoreBrandConfig>lambdaQuery()
                .eq(ChannelStoreBrandConfig :: getMerId, merId)
                );
        List<Integer> configIds = configs.stream().map(obj -> obj.getBrandId()).collect(Collectors.toList());
        StoreBrandRequest brandBequest = new StoreBrandRequest();
        brandBequest.setIds(configIds);
        brandBequest.setIsAdvice(1);
        response.setStoreBrandList(storeBrandService.selectStoreBrandList(brandBequest));
        return response;
    }

    @Override
    public IndexAdviceResponse getZoneList(Integer merId) {
        IndexAdviceResponse response = new IndexAdviceResponse();
        //获取专区配置
        response.setStoreZoneStatus(1);
        //查询导航栏专区数据
        LambdaQueryWrapper<StoreZone> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StoreZone::getMerId,merId);
        queryWrapper.eq(StoreZone::getIsDel,0);//未删除
//            queryWrapper.eq(StoreZone::getIsAppBar,1);//导航专区展示
        queryWrapper.gt(StoreZone::getEndTime,new Date());
        queryWrapper.orderByDesc(StoreZone::getSort).orderByDesc(StoreZone::getUpdateTime);
        List<StoreZone> storeZoneList = storeZoneService.list(queryWrapper);

        List<StoreZone> newStoreZoneList =  new ArrayList<StoreZone>();

        for (StoreZone storeZone :storeZoneList){

            //查询商品
            ProductRequest request = new ProductRequest();
            request.setZoneId(storeZone.getId());
            request.setMerId(merId);
            request.setShowIds(Collections.singletonList(0));
            request.setTableNameMp(TableNameUtil.getProductMerName(merId));

            List<StoreProduct> storeProductList = storeProductDao.selectZoneProductList(request);

            if(storeProductList.size()>0){
                newStoreZoneList.add(storeZone);
            }
        }

        response.setStoreZoneList(newStoreZoneList);
        //获取首页专区
        LambdaQueryWrapper<StoreZone> storeZoneLambdaQueryWrapper = new LambdaQueryWrapper<>();
        storeZoneLambdaQueryWrapper.eq(StoreZone::getMerId,merId);
        storeZoneLambdaQueryWrapper.eq(StoreZone::getIsDel,0);//未删除
        storeZoneLambdaQueryWrapper.eq(StoreZone::getStatus,1);//首页展示
        storeZoneLambdaQueryWrapper.gt(StoreZone::getEndTime,new Date());
        storeZoneLambdaQueryWrapper.orderByDesc(StoreZone::getUpdateTime);
        storeZoneLambdaQueryWrapper.last("LIMIT 1");
        StoreZone storeZone = storeZoneService.getOne(storeZoneLambdaQueryWrapper);
        IndexProductStoreZoneResponse indexStoreZoneResponse = new IndexProductStoreZoneResponse();
        indexStoreZoneResponse.setStoreZone(storeZone);
        //查询对应专区下的商品
        if (storeZone != null){
            //查询未上架的商品ids
            ProductRequest request = new ProductRequest();
            request.setZoneId(storeZone.getId());
            request.setMerId(merId);
            request.setShowIds(Collections.singletonList(0));
            request.setTableNameMp(TableNameUtil.getProductMerName(merId));
            PageHelper.startPage(1, 4);//查询四条专区对应商品信息
            List<StoreProduct> storeProductList = storeProductDao.selectZoneProductList(request);
            indexStoreZoneResponse.setStoreProductList(storeProductList);
        }
        response.setIndexProductStoreZoneResponse(indexStoreZoneResponse);
        //首页分类推荐
        List<ChannelCategoryConfig> cateConfigs = channelCategoryConfigService.list(Wrappers.<ChannelCategoryConfig>lambdaQuery()
                .eq(ChannelCategoryConfig :: getMerId, merId)
                .eq(ChannelCategoryConfig::getIsAdvice,1)
                .eq(ChannelCategoryConfig::getStatus,1)
                .eq(ChannelCategoryConfig::getEnableFlag,1)
                .orderByDesc(ChannelCategoryConfig::getAdviceTime)
        );
        List<Integer> ids = cateConfigs.stream().map(ChannelCategoryConfig::getCateId).collect(Collectors.toList());
        List<Category> categoryList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(ids)){
            CategorySearchRequest categoryRequest = new CategorySearchRequest();
            categoryRequest.setIds(ids);
            categoryRequest.setType(1);
            categoryRequest.setStatus(true);
            categoryList = categoryService.getList(categoryRequest, new PageParamRequest());
            categoryList.sort(((o1, o2) -> {
                int io1 = ids.indexOf(o1.getId());
                int io2 = ids.indexOf(o2.getId());
                return io1 - io2;
            }));
        }
        response.setCategoryList(categoryList);
        // 获取商户品牌配置项
        List<ChannelStoreBrandConfig> configs = channelStoreBrandConfigService.list(Wrappers.<ChannelStoreBrandConfig>lambdaQuery()
                .eq(ChannelStoreBrandConfig :: getMerId, merId)
                );
        List<Integer> configIds = configs.stream().map(obj -> obj.getBrandId()).collect(Collectors.toList());
        StoreBrandRequest brandBequest = new StoreBrandRequest();
        brandBequest.setIds(configIds);
        brandBequest.setIsAdvice(1);
        response.setStoreBrandList(storeBrandService.selectStoreBrandList(brandBequest));
        return response;
    }

    @Override
    public StoreZone getZoneById(Integer id) {
        return storeZoneService.getById(id);
    }

}

